package com.jysz.certificate.web.action.system;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Set;

import javax.annotation.Resource;

import org.apache.commons.lang.StringUtils;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Namespace;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.config.ConfigurableBeanFactory;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.jysz.certificate.action.AbstractBaseAction;
import com.jysz.certificate.persistence.model.system.Financial;
import com.jysz.certificate.persistence.model.system.Shop;
import com.jysz.certificate.persistence.model.system.Treaty;
import com.jysz.certificate.persistence.model.system.User;
import com.jysz.certificate.service.cs.CheckStockService;
import com.jysz.certificate.service.system.FinancialService;
import com.jysz.certificate.service.system.OrganizationService;
import com.jysz.certificate.service.system.ShopService;
import com.jysz.certificate.service.system.TreatyService;
import com.jysz.certificate.service.system.UserService;
import com.jysz.certificate.utils.DateUtil;
import com.jysz.certificate.web.action.Excel.ExcelSheetParser;
import com.jysz.webcore.ssh.orm.hibernate.support.Page;

@Controller
@Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE)
@Namespace("/system/treaty")
public class TreatyAction  extends AbstractBaseAction{
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	@Resource
	private TreatyService treatyService;
	@Resource
	private CheckStockService csService;
	@Resource
	private ShopService shopService;
	@Resource
	private FinancialService financialService;
	@Resource
	private OrganizationService organizationService;
	@Resource
	private UserService userService;
	private Treaty treaty;
	private Treaty treaty2;
	private Treaty treatyDTO;
	private Page<Shop> pg;
	private List<Financial> listFinancials;
	private Shop shopDto;
	private Long shopID;
	private Long financialId;
	private String shopName;
	private Double floorsD;
	private File file;
	private String allIds;
	private Date benginDate;
	private String versionMark;
	private Boolean foreignReserves;
	private Long id;
	private Long shopUserId;
	private String shopUserName;
	
	@Action(ADD)//新增页面**协议
	public String add() {
		this.setPage(shopService.findPage(this.getCurrentPage(), this.getPageSize()));
		listFinancials=financialService.finList();
		treaty2=new Treaty();
		treaty2.setFloors(0.0);
		treaty2.setUnitPrice(0.0);
		treaty2.setMaximum(0.0);
		treaty2.setStartDate(new Date());
		treaty2.setEndDate(DateUtil.addYears(new Date(), 1));
		setRedirectUrl("index.do?currentPage="+getCurrentPage(),"treatyDTO",treatyDTO);
		return ADD;
	}
	@Action("selectCheckShop")//组织架构选择店铺
	public String selectCheckShop() {
		this.setPage(shopService.selectUser(null,shopDto, null, this.getCurrentPage(), this.getPageSize()));
		return "selectCheckShop";
	}
	@Action("selectCheckShopUser")//用户选择店铺
	public String selectCheckShopUser() {
		this.setPage(organizationService.selectShopUser(shopName,this.getCurrentPage(), this.getPageSize()));
		return "selectCheckShopUser";
	}
	@Action("selectShop")//**选择店铺
	public String selectShop() {
		Set<Long> shopIdLongs = organizationService.fianPage(getUser());
		if(null == shopIdLongs){
			this.setPage(null);
			return "selectShop";
		}
		this.setPage(shopService.selectUser(shopIdLongs,shopDto, null, this.getCurrentPage(), this.getPageSize()));
		return "selectShop";
	}
	
	/**
	 * 盘库新增时选择店铺-专用
	 * @return
	 */
	@Action("selectCheckStockShop")
	public String selectCheckStockShop() {
		Set<Long> shopIdLongs = organizationService.fianPage(getUser());
		if(null == shopIdLongs){
			this.setPage(null);
			return "selectCheckStockShop";
		}
		User shopUser=null;
		if(shopUserId!=null){
			shopUser=userService.find(shopUserId);
		}
		this.setPage(shopService.selectCfShop(shopIdLongs,shopDto,shopUser, this.getCurrentPage(), this.getPageSize()));
		return "selectCheckStockShop";
	}
	
	//查询最近盘库日期
	public String getCheckStockDate(Long shopId){
		return csService.findCloseCheckStockDate(shopId, getUser());
	}
	
	@Action("selectAll")//查询页面**协议--所有
	public String selectAll() {
		this.setPage(treatyService.selectAll(this.getCurrentPage(), this.getPageSize()));
		return INDEX;
	}
	@Action(INDEX)//查询页面**协议--条件
	public String index() {
		if(versionMark != null && StringUtils.isNotBlank(versionMark)){
			if(versionMark.equals("true")){
				treatyDTO.setMark(true);
			}else{
				treatyDTO.setMark(false);
			}
			
		}else{
			if(treatyDTO != null){
				treatyDTO.setMark(null);
			}
		}
		listFinancials=financialService.finList();
		this.setPage(treatyService.selectTR(treatyDTO, getCurrentPage(),  getPageSize(), floorsD, floorsX));
		return INDEX;
	}
	@Action("minute")//查询页面**协议--详情
	public String minute() {
		listFinancials=financialService.finList();
		this.setPage(shopService.findPage(this.getCurrentPage(), this.getPageSize()));
		treaty2=treatyService.find(treaty.getId());
		if(treaty2.getFloors()==null){
			treaty2.setFloors(0.0);
		}
		if (treaty2.getUnitPrice()==null) {
			treaty2.setUnitPrice(0.0);
		}
		if (treaty2.getMaximum()==null) {
			treaty2.setMaximum(0.0);
		}
		setRedirectUrl("index.do?currentPage="+getCurrentPage(),"treatyDTO",treatyDTO);
		return ADD;
	}
	/**
	 * 新增协议
	 * 
	 * @return
	 */
	@Action("save")
	public String save() {
		Shop shopq=new Shop();
		boolean bo = false;
		Treaty target = new Treaty();
		shopq.setId(shopID);
		treaty.setShop(shopq);
		if(treaty.getId()!= null){
			target = treatyService.find(treaty.getId());
			
		}else{
			treaty.setMark(treatyService.whetherThere(shopID, treaty.getFinancial().getId()));
		}
		String ary[]=new String[]{"id","createdAt","creator"};
		BeanUtils.copyProperties(treaty,target, ary);
		try {
			treatyService.save(target);
			treaty=new Treaty();
			setSuccessPopMessage("更新数据成功");
			return SHOW_MSG_PAGE;
		} catch (Exception e) {
			setSuccessPopMessage("更新数据失败");
			return SHOW_MSG_PAGE;
		}
		
		
	}
	/**
	 * 验证协议是否同时存在两份有效地协议
	 * @return
	 */
	@Action("efficacyTreaty")
	public String efficacyTreaty() {
		Gson gson = new GsonBuilder().excludeFieldsWithoutExposeAnnotation().create();
		if(!foreignReserves){
			this.setJsonText(gson.toJson(false));
			return JSON_PAGE;
		}
		boolean bo = treatyService.whetherThere(shopID, financialId, benginDate,id);
		
		this.setJsonText(gson.toJson(bo));
		return JSON_PAGE;
	}
	/**
	 * 验证协议是否同时存在两份有效地协议  有  则 禁用
	 * @return
	 */
	@Action("forbiddenTreaty")
	public String forbiddenTreaty() {
		Gson gson = new GsonBuilder().excludeFieldsWithoutExposeAnnotation().create();
		List<Treaty> treaties = treatyService.whetherTheres(shopID, financialId, benginDate);
		for(Treaty treaty : treaties){
			if(null == id){
				treaty.setState(false);
				
				treatyService.save(treaty);
			}else if(treaty.getId() != id){
				treaty.setState(false);
				
				treatyService.save(treaty);
			}
		}
		
		this.setJsonText(null);
		return JSON_PAGE;
	}
	/**
	 * 导入协议
	 * @return
	 */
	@Action("importTreaty")
	public String importTreaty(){
		boolean mark = true;
		List<Treaty> treaties = treatyService.findAll();
		List<Treaty> listTreaty=new ArrayList<Treaty>();
		try {
			ExcelSheetParser excelSheetParser=new ExcelSheetParser(file);
			List<List> datas =excelSheetParser.getDatasInSheet(0);//获得导入文件中所有数据
			List listB=datas.get(0);
			 String table="店号,签约销售店,合作银行,综合授信协议编号,管理费收取方式,管理费标准(保底数),单证释放价,签订协议时间／展业时间,协议结束时间,广爱有否有协议存底,客户经理,备注,管理费最大数";
			 String[] ta=table.split(",");
			for(int i=0;i<listB.size();i++){
				if(ta.length+1!=listB.size()){
					this.addActionError("文件不匹配，请确认导入文件是协议文件\n");
					 mark = false;
					 break;
				}
				if(i!=listB.size()-1){
					String values=String.valueOf(listB.get(i));
					if(!ta[i].equals(values)){
						this.addActionError("第1行，第"+(i+1)+"列,导入文件表头存在错误\n");
						 mark = false;
						   continue;
					}
				}
			}
		if(mark){
			for(int i=1;i<datas.size();i++){//循环所有数据行
				List row=datas.get(i);//获得单行数据
				String val=null;//暂时保存的单元格数据
				Shop shop=null;
				Treaty treaty=null;
				treaty=new Treaty();
				for(int j=0;j<row.size();j++){//循环每行的数据
					
					val=String.valueOf(row.get(j));//获得单元格数据
					if(j==0 && !val.equals("null")){
						shop=shopService.shopNamekKey(val);
						if(shop==null){
							this.addActionError("第"+(i+1)+"行，第"+(j+1)+"列,"+val+"店号不存在\n");
							 mark = false;
							   continue;
						}
						treaty.setShop(shop);
					}else if(j==1 && !val.equals("null")){
						if(shop!=null){
						if(!shop.getCompany().equals(val)&&!shop.getShopName().equals(val)){//判断店号 店名是否匹配
							 this.addActionError("第"+(i+1)+"行，第"+(j+1)+"列,店名:"+val+"  与 店号: "+shop.getShopMark()+"  不匹配\n");
							 mark = false;
							   continue;
						 }
						}
					}else if(j==2){
						treaty.setBranch(val);
					}else if(j==3 && !val.equals("null")){
						Treaty tr=treatyService.shopNameKey(val);
						if(tr!=null){
							 this.addActionError("第"+(i+1)+"行，第"+(j+1)+"列,协议编号:"+val+"  重复\n");
							 mark = false;
							   continue;
						}
						treaty.setIdentifier(val);
					}else if(j==4){
						if(val.equals("null")){
							treaty.setCollectionWay(null);
						}else{
							if(val.equals("月付")){
								treaty.setCollectionWay("0");
							}else if(val.equals("季付")){
								treaty.setCollectionWay("1");
							}else if(val.equals("半年付")){
								treaty.setCollectionWay("2");
							}else{
								this.addActionError("第"+(i+1)+"行，第"+(j+1)+"列,管理费收取方式只能为：月付     季付  半年付     不能为："+val+"\n");
								 mark = false;
								   continue;
							}
						}
					}else if(j==5){
						if(!val.equals("null")){
						try {
							 double dou=Double.valueOf(val).doubleValue();
								treaty.setFloors(dou);
						} catch (Exception e) {
							 this.addActionError("第"+(i+1)+"行，第"+(j+1)+"列, 保底数： "+val+"       数据错误\n");
							 mark = false;
							   continue;
						}
						}else{
						treaty.setFloors(0D);
						}
					}else if(j==6){
						if(!val.equals("null")){
							try {
								 double dou=Double.valueOf(val).doubleValue();
									treaty.setUnitPrice(dou);
							} catch (Exception e) {
								 this.addActionError("第"+(i+1)+"行，第"+(j+1)+"列, 单证释放价： "+val+"       数据错误\n");
								 mark = false;
								   continue;
							}
						}else{
						treaty.setUnitPrice(0D);
						}
					}else if(j==7){
						if(!val.equals("null")){
						 SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
						 try {
							Date date = sdf.parse(val);
							treaty.setStartDate(date);
						} catch (ParseException e) {
							this.addActionError("第"+(i+1)+"行，第"+(j+1)+"列,签订时间:  "+val+"  数据错误\n");
							 mark = false;
							 continue;
						}
						}else{
							this.addActionError("第"+(i+1)+"行，第"+(j+1)+"列,签订时间: 不能为空\n");
							 mark = false;
							 continue;
						}
							
					}else if(j==8 && !val.equals("null")){
						if(treaty.getStartDate()!=null){
							if(val.equals("null")&&treaty.getStartDate()!=null){
								treaty.setEndDate(DateUtil.addYears(treaty.getStartDate(),1));
							}else{
							 SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
							 try {
								 
								Date date = sdf.parse(val);
								treaty.setEndDate(date);
								if(DateUtil.isSameDay(treaty.getStartDate(), treaty.getEndDate())||DateUtil.isNotBeforeEndTime(treaty.getStartDate(), treaty.getEndDate())){
									this.addActionError("第"+(i+1)+"行，第"+(j+1)+"列,结束时间晚于签订时间\n");
									 mark = false;
									 continue;
								}
							} catch (ParseException e) {
								this.addActionError("第"+(i+1)+"行，第"+(j+1)+"列,结束时间:  "+val+"  数据错误\n");
								 mark = false;
								 continue;
							}
							}
						}
						
							
					}else if(j==9){
						if(val.equals("null")){
							treaty.setForeignReserves(null);
						}else if(val.equals("是")){
							treaty.setForeignReserves("0");
						}else if(val.equals("返还")){
							treaty.setForeignReserves("1");
						}else{
							this.addActionError("第"+(i+1)+"行，第"+(j+1)+"列,是否有存底只能为：是       返还    不能为："+val+"\n");
							 mark = false;
							   continue;
						}
					}else if(j==10){
						if(val.equals("null")){
							val = null;
						}
						treaty.setManager(val);
					}else if(j==11){
						if(val.equals("null")){
							val = null;
						}
						treaty.setRemark(val);
					}else if (j==12){
						if(!val.equals("null")){
							try {
								 double dou=Double.valueOf(val).doubleValue();
									treaty.setMaximum(dou);
							} catch (Exception e) {
								 this.addActionError("第"+(i+1)+"行，第"+(j+1)+"列, 管理费最大数： "+val+"       数据错误\n");
								 mark = false;
								   continue;
							}
						}else{
						treaty.setMaximum(0D);
						}
					}else if((j+1)!=row.size()&&j<13){
						this.addActionError("第"+(i+1)+"行，第"+(j+1)+"列,数据错误或者不能为空\n");
						   mark = false;
						   continue;
					}
					
				}
				if(mark){
					Financial financial=new Financial();
					financial.setId(financialId);
					treaty.setFinancial(financial);
					if(treatyService.whetherThere(treaty.getShop().getId(), financialId, treaty.getEndDate(),null)){
						this.addActionError(treaty.getShop().getShopName()+"  与    "+financialService.fianName(financialId)+"  存在生效的协议\n");
						   mark = false;
						   continue;
					}else{
						boolean dol = true;
						for(int y =0 ;y<treaties.size() ;y++){
							Treaty treaty2 = treaties.get(y);
							if(financialId == treaty2.getFinancial().getId() && treaty.getShop().getId() == treaty2.getShop().getId()){
								dol =false;
							}
						}
							treaty.setMark(dol);
						listTreaty.add(treaty);
					}
					
				}
			}
			}
		}catch (FileNotFoundException e) {
			e.printStackTrace();
			System.out.println("文件没找到 : " + e);  
		} catch (IOException e) {
			this.addActionError("文件不匹配, 请确认导入文件是合格证导入文件\n");
			 mark = false;
		}
		if(mark){
			for(int i=0;i<listTreaty.size();i++){
				Treaty cf=listTreaty.get(i);
				cf.setState(true);
				treatyService.save(cf);
			}
			setSuccessPopMessage("导入数据成功\n       本次成功导入："+listTreaty.size());
			return SHOW_MSG_PAGE;
			
		}else {
			return this.toImport();
		}
	}
	@Action("toImport")
	public String toImport(){
		listFinancials=financialService.finList();
		setRedirectUrl("index.do?currentPage="+getCurrentPage(),"treatyDTO",treatyDTO);
		return "tolead";
	}
	public TreatyService getTreatyService() {
		return treatyService;
	}
	public void setTreatyService(TreatyService treatyService) {
		this.treatyService = treatyService;
	}
	public ShopService getShopService() {
		return shopService;
	}
	public void setShopService(ShopService shopService) {
		this.shopService = shopService;
	}
	public List<Financial> getListFinancials() {
		return listFinancials;
	}
	public void setListFinancials(List<Financial> listFinancials) {
		this.listFinancials = listFinancials;
	}
	public Date getBenginDate() {
		return benginDate;
	}
	public void setBenginDate(Date benginDate) {
		this.benginDate = benginDate;
	}
	public Treaty getTreatyDTO() {
		return treatyDTO;
	}
	public void setTreatyDTO(Treaty treatyDTO) {
		this.treatyDTO = treatyDTO;
	}
	public Long getId() {
		return id;
	}
	public void setId(Long id) {
		this.id = id;
	}
	public Boolean getForeignReserves() {
		return foreignReserves;
	}
	public void setForeignReserves(Boolean foreignReserves) {
		this.foreignReserves = foreignReserves;
	}
	public String getVersionMark() {
		return versionMark;
	}
	public void setVersionMark(String versionMark) {
		this.versionMark = versionMark;
	}
	public String getAllIds() {
		return allIds;
	}
	public void setAllIds(String allIds) {
		this.allIds = allIds;
	}
	public String getShopName() {
		return shopName;
	}
	public void setShopName(String shopName) {
		this.shopName = shopName;
	}
	public Shop getShopDto() {
		return shopDto;
	}
	public void setShopDto(Shop shopDto) {
		this.shopDto = shopDto;
	}
	public Treaty getTreaty2() {
		return treaty2;
	}
	public void setTreaty2(Treaty treaty2) {
		this.treaty2 = treaty2;
	}
	public Long getFinancialId() {
		return financialId;
	}
	public void setFinancialId(Long financialId) {
		this.financialId = financialId;
	}
	public File getFile() {
		return file;
	}
	public void setFile(File file) {
		this.file = file;
	}
	public Double getFloorsD() {
		return floorsD;
	}
	public void setFloorsD(Double floorsD) {
		this.floorsD = floorsD;
	}
	public Double getFloorsX() {
		return floorsX;
	}
	public void setFloorsX(Double floorsX) {
		this.floorsX = floorsX;
	}
	private Double floorsX;

	 
	public Long getShopID() {
		return shopID;
	}
	public void setShopID(Long shopID) {
		this.shopID = shopID;
	}
	
	public Page<Shop> getPg() {
		return pg;
	}
	public void setPg(Page<Shop> pg) {
		this.pg = pg;
	}
	public Treaty getTreaty() {
		return treaty;
	}
	public void setTreaty(Treaty treaty) {
		this.treaty = treaty;
	}
	public Long getShopUserId() {
		return shopUserId;
	}
	public void setShopUserId(Long shopUserId) {
		this.shopUserId = shopUserId;
	}
	public String getShopUserName() {
		return shopUserName;
	}
	public void setShopUserName(String shopUserName) {
		this.shopUserName = shopUserName;
	}
}
